/*
 * Created on 2005-5-6
 *
 */
package com.hd123.rumba.request;

import net.sf.hibernate.HibernateException;

import org.apache.axis.AxisFault;
import org.apache.log4j.Logger;

import com.hd123.rumba.domain.IDomain;
import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.exception.NoAccessException;
import com.hd123.rumba.runtime.HibernateSession;
import com.hd123.rumba.runtime.NamingMgr;
import com.hd123.rumba.user.IUser;
import com.hd123.rumba.user.IUserMgr;
import com.hd123.rumba.user.LoginResult;

/**
 * @author caili
 */
public class SessionedService {

  /**
   * 登录
   * 
   * @param login
   * @param password
   * @param domainId
   * @return
   * @throws AxisFault
   */
  public boolean login(String login, String password, String domainId) throws AxisFault {
    try {
      LoginResult loginResult = ((IUserMgr) NamingMgr.getInstance().lookupMgr(IUserMgr.class))
          .login(login, password, domainId);
      if (loginResult.isError()) {
        Logger.getLogger(this.getClass()).info(
            "登录失败:" + login + "@" + domainId + ", " + loginResult.getErrorText());
        return false;
      }
      AxisSession.setCurrentDomain(loginResult.getDomain());
      AxisSession.setCurrentUser(loginResult.getUser());
      AxisSession.setEnterpriseDomain(loginResult.getEnterpriseDomain());
      Logger.getLogger(this.getClass()).info("登录成功:" + login + "@" + domainId);
      return true;
    } catch (BusinessException e) {
      throw AxisFault.makeFault(e);
    } finally {
      try {
        HibernateSession.closeSession();
      } catch (HibernateException ex) {
        throw AxisFault.makeFault(ex);
      }
    }
  }

  /**
   * 返回是否已经登录
   * 
   * @return
   */
  public boolean isLogin() {
    return getCurrentUser() != null;
  }

  /**
   * 检查是否可以调用此方法
   * 
   * @param action
   * @throws AxisFault
   */
  protected void checkAccess(String action) throws AxisFault {
    if (getCurrentUser() == null) {
      throw AxisFault.makeFault(new NoAccessException("未登录"));
    }
    // if (!ActionAcl.getInstance().hasAcl(getCurrentUser(), action)) {
    // throw AxisFault.makeFault(new NoAccessException("没有权限"));
    // }
  }

  protected IUser getCurrentUser() {
    return AxisSession.getCurrentUser();
  }

  protected IDomain getCurrentDomain() {
    return AxisSession.getCurrentDomain();
  }

  protected IDomain getEnterpriseDomain() {
    return AxisSession.getEnterpriseDomain();
  }

}
